<?php

namespace App\Http\Controllers\Api;

use App\Comment;
use App\Goods;
use App\OrderGoods;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

class CommentController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $comments = Comment::latest()->with(['user' => function($query) {
            return $query->select('id', 'name', 'avatar');
        }])->with(['orderGoods']);
        if ($request->goods_id) {
            $comments->where('goods_id', $request->goods_id);
        }
        return $comments->paginate(20);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $data = $request->all();
        $orderGoods = OrderGoods::where('goods_id', $request->goods_id)->where('order_id', $request->order_id)->first();
        $data['user_id'] = Auth::id();
        $data['order_goods_id'] = $orderGoods->id;
        Comment::create($data);
        if ($request->goods_id && $request->order_id && $orderGoods) {
            $orderGoods->commented_at = Carbon::now();
            $orderGoods->save();
            Goods::where('id', $request->goods_id)->increment('comment_count');
        }
        return response(['message' => '创建成功']);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Comment  $comment
     * @return \Illuminate\Http\Response
     */
    public function show(Comment $comment)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Comment  $comment
     * @return \Illuminate\Http\Response
     */
    public function edit(Comment $comment)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Comment  $comment
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Comment $comment)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Comment  $comment
     * @return \Illuminate\Http\Response
     */
    public function destroy(Comment $comment)
    {
        //
    }
}
